﻿using System;
using System.Web;
using System.Web.Security;
using Foothill.Common;
using Foothill.IoC;
using Foothill.Model;
using Foothill.Service.UserAccount;

namespace Foothill.Web.Login
{
    public partial class Login : FoothillBasePage
    {
        private IAuthenticationService _authenticationService;
        
        protected void Page_Load(object sender, EventArgs e)
        {
            _authenticationService = IocContainer.GetInstance<IAuthenticationService>();
            lblLoginError.Visible = false;
        }

        protected void btnLoginClick(object sender, EventArgs e)
        {
            string errorMessage;
            CurrentLoginUser loginUser;

            AuthenticationResult authResult = _authenticationService.AuthenticateUser(txtEmail.Text.Trim(), txtPassword.Text.Trim(), out loginUser, out errorMessage);

            if (authResult.AuthenticateUser)
            {
                // login ok, create authentication ticket and add it to response
                string authTicket = _authenticationService.CreateEncryptedAuthenticationTicket(loginUser.UserAccountInfo.Username);

                Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, authTicket));

                if (!authResult.TempPasswordUsed)
                {
                    Response.Redirect("~/ForSaleList/ForSaleList.aspx");
                }
                else
                {
                    // todo: redirect to change temp password page
                    Response.Redirect("~/ChangeTempPassword/ChangeTempPassword.aspx");
                }
            }
            else
            {
                // display error
                lblLoginError.Visible = true;
                lblLoginError.Text = errorMessage;
            }
        }

        protected void lbtForgotPasswordClick(object sender, EventArgs e)
        {
            string url = "~/RecoverPassword/RecoverPassword.aspx";

            string email = txtEmail.Text.Trim();
            if (!string.IsNullOrWhiteSpace(email))
            {
                url += string.Format("?{0}={1}", GlobalQueryString.RecoverPwdEmailQsName, Server.HtmlEncode(email));
            }

            Response.Redirect(url);
        }
    }
}